import {pinus} from 'pinus';
import {preload} from './preload';
import {TimeOutFilter} from "./app/util/timeOutFilter";
import RouteUtil from "./app/util/routeUtil";
import * as sync from "pomelo-sync-plugin";
import MysqlPool from "./app/dao/mysql/mysqlPool";
import {svrInit} from "./app/util/srvInit";

/**
 *  替换全局Promise
 *  自动解析sourcemap
 *  捕获全局错误
 */
preload();

/**
 * 转换加载pomole插件
 * @param plugin
 * @param name
 * @param fileName
 */
function change(plugin, name, fileName) {
    const componentsPath = plugin.components;
    plugin.components = [require(componentsPath + '/' + fileName)];

    if (plugin && plugin.hasOwnProperty("events") && plugin.events) {
        const eventsPath = plugin.events;
        plugin.events = [require(eventsPath + '/event')]
    } else {
        plugin.events = [];
    }
    plugin.name = name
}
change(sync, "pomelo-sync-plugin", "sync");


/**
 * Init app for client.
 */
let app = pinus.createApp();
app.set('name', 'esportsManager');


/**
 * 设置路由
 */
app.configure('production|development', 'all', async function () {

    app.filter(new TimeOutFilter());                       // 增加一个过滤器
    app.route('area', RouteUtil.area);         // 设置area服务器路由

    svrInit(app);
});


/**
 *  gate服务 主要用于connector服务器的负载均衡
 */
app.configure('production|development', 'gate', function () {

    app.set('connectorConfig', {
        connector: pinus.connectors.hybridconnector,
        heartbeat: 3,
        useDict: true,      // 启用字典压缩
        useProtobuf: true,  // 启用protobuf
    });

});


/**
 * connector服务 主要用于创建与客户端的连接，维护客户端的session信息
 */
app.configure('production|development', 'connector', function () {

    app.set('connectorConfig', {
        connector: pinus.connectors.hybridconnector,        // 设置连接方式
        heartbeat: 3,
        useDict: true,
        useProtobuf: true
    });

});


/**
 * area服务 大厅服务器 用来储存场景信息, 处理客户端的请求, 如用户添加, 删除, 攻击等操作
 */
app.configure('production|development', 'area', function () {

    app.set('connectorConfig', {
        connector: pinus.connectors.hybridconnector,
        useProtobuf: true
    });

});


/**
 * dao服务 主要用于数据库操作
 */
app.configure('production|development', 'dao', function () {

    app.loadConfig('mysql', `${app.getBase()}/config/mysql/mysql.json`);

    let dbClient = new MysqlPool(app.get('mysql'),"esports");
    app.set('dbClient', dbClient);

    // 创建serverDB
    let serverDBClient = new MysqlPool(app.get('mysql'),"server");
    app.set('serverDBClient', serverDBClient);

});


// start app
app.start();

